package com.core.controller;

import com.core.annotation.OperationLog;
import com.core.domain.User;
import com.core.dto.UserInfoDto;
import com.core.resp.AjaxResponse;
import com.core.resp.PageResult;
import com.core.service.UsersService;
import com.core.vo.UserRolesVo;
import com.core.vo.UserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @author : HUANG
 * @create : 2025/6/1 22:12
 * @function :
 */
@RequestMapping("/user")
@RestController
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UsersService usersService;

    @GetMapping("/get/{username}")
    @OperationLog(type = "read", module = "user", description = "查看用户详情: #username")
    public AjaxResponse getUser(@PathVariable String username) {
        User user = usersService.selectByUsername(username);
        return AjaxResponse.success(200, "查询成功", user);
    }

    @PostMapping("/get/{pageSize}/{pageNum}")
    @OperationLog(type = "list", module = "user", description = "分页查询用户列表")
    public AjaxResponse getUsers(@RequestBody User user, @PathVariable Long pageNum, @PathVariable Long pageSize) {
        PageResult<UserInfoDto> userList = usersService.getUserListPage(user, pageSize, pageNum);
        return AjaxResponse.success(200, "查询成功", userList);
    }

    @PreAuthorize("@ss.hasAuthority('user:create')")
    @PostMapping("/add")
    @OperationLog(type = "create", module = "user", description = "添加用户: #user.username")
    public AjaxResponse addUser(@RequestBody @Validated UserVo user) {
        try {
            return usersService.addUser(user);
        } catch (Exception e) {
            if (e.getMessage().contains("Duplicate entry")) {
                return AjaxResponse.error(405, "用户名已经存在");
            } else {
                return AjaxResponse.error(500, "服务器出错保存失败");
            }
        }
    }

    @PreAuthorize("@ss.hasAuthority('user:update')")
    @PutMapping("/updateRoles/{userId}")
    @OperationLog(type = "update", module = "user", description = "更新用户角色, 用户ID: #userId, 角色IDs: #userRolesVo.roles")
    public AjaxResponse putUser(@PathVariable Long userId, @RequestBody UserRolesVo userRolesVo) {
        AjaxResponse ajaxResponse = usersService.updateRoles(userId, userRolesVo);
        return ajaxResponse;
    }

    @PreAuthorize("@ss.hasAuthority('user:delete')")
    @OperationLog(type = "delete", module = "user", description = "更新用户角色, 用户ID: #userId, 角色IDs: #userRolesVo.roles")
    @PostMapping("/batchDelete")
    public AjaxResponse deleteUser(@NotNull(message = "删除数据不能为空") @RequestBody List<Long> userIds) {
        try {
            usersService.deleteUser(userIds);
        } catch (Exception e) {
            log.error(e.getMessage());
            return AjaxResponse.error(405, "删除失败");
        }
        return AjaxResponse.success(200, "删除成功", null);
    }
}
